package com.zl.dao;

import java.lang.reflect.Parameter;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;

import com.zl.domain.PageBean;
/*
 * 以后dao实现类都可以继承basedaoimpl
 */
@SuppressWarnings("all")
public class BaseDaoImpl<T>extends HibernateDaoSupport implements BaseDao<T>{

	
	private Class clazz;
	
	public BaseDaoImpl() {
//		System.out.println("，，，，，");
		//this表示的是子类 此类是由子类创建二创建的  多态
		Class c = this.getClass();
		Type type = c.getGenericSuperclass();
		
		//把接口转成子接口
		if (type instanceof ParameterizedType) {
			ParameterizedType ptype = (ParameterizedType)type;
			
			//获取到泛型
			Type[] types = ptype.getActualTypeArguments();
			this.clazz = (Class)types[0];
		}
		
	}
	/**
	 * 添加
	 */
	@Override
	public void save(T t) {
		// TODO Auto-generated method stub
		this.getHibernateTemplate().save(t);
	}
	/**
	 * 删除
	 */
	@Override
	public void delete(T t) {
		// TODO Auto-generated method stub
		this.getHibernateTemplate().delete(t);
	}
	/**
	 * 修改
	 */
	@Override
	public void update(T t) {
		// TODO Auto-generated method stub
		this.getHibernateTemplate().update(t);
	}
	/**
	 * 通过主键查询
	 */
	@Override
	public T findById(Long id) {
		// TODO Auto-generated method stub
		
		return (T) this.getHibernateTemplate().get(clazz, id);
	}

	@Override
	public List<T> findAll() {
		// TODO Auto-generated method stub
		return (List<T>) this.getHibernateTemplate().find("from "+clazz.getSimpleName());
	}
	/**
	 * 分页
	 */

	@Override
	public PageBean<T> findByPage(Integer pageCode, Integer pageSize, DetachedCriteria criteria) {
		// TODO Auto-generated method stub
		//创建分页对象
		PageBean<T> pageBean = new PageBean<T>();
		pageBean.setPageCode(pageCode);
		pageBean.setPageSize(pageSize);
		
		//总记录数
		criteria.setProjection(Projections.rowCount());
		List<Number> list = (List<Number>) this.getHibernateTemplate().findByCriteria(criteria);
		if (list != null && list.size()>0) {
			int totalCount = list.get(0).intValue();
			pageBean.setTotalCount(totalCount);
		}
		
		//每页显示的数据
		criteria.setProjection(null);
		List<T> list2 = (List<T>) this.getHibernateTemplate().findByCriteria(criteria, (pageCode-1)*pageSize, pageSize);
		pageBean.setBeanList(list2);
		
		return pageBean;
	}

}
